import { Tooltip } from "antd"
import React, { useState } from "react"
import { useId } from "react"

import { STooltipContainer, TextLength } from "./index.styled"

const TooltipText = ({ text, width, children }: { text: React.ReactNode; width?: number; children?: React.ReactNode }) => {
	const [isHovered, setIsHovered] = useState(false)
	const id = useId()
	const idTest = useId()

	const handleHover = () => {
		const realTextWidth = document.getElementById(idTest)?.offsetWidth || 0
		const textContainerWidth = width || document.getElementById(id)?.clientWidth || 0

		if (realTextWidth > textContainerWidth) {
			setIsHovered(true)
		}
	}

	const widthStyle = width ? { width } : {}

	return (
		<>
			<Tooltip title={text} open={isHovered}>
				<STooltipContainer
					style={widthStyle}
					className="text-container"
					id={id}
					onMouseEnter={handleHover}
					onMouseLeave={() => setIsHovered(false)}
				>
					{children || text}
				</STooltipContainer>
			</Tooltip>
			<TextLength className="tooltip-text-real" id={idTest}>
				{text}
			</TextLength>
		</>
	)
}

export default TooltipText
